<?php

namespace App\Pay;

use App\Model\PayHttpLog;
use App\Service\HttpService;
use GuzzleHttp\Exception\GuzzleException;
use http\Client;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Guzzle\ClientFactory;
use Hyperf\Testing\HttpClient;

class Airwallex
{
    private $clientId = 'eb3H0trTS3GZHxJ2FbqraQ';
    private $apiKey = '5a42bf77e6fe27669fa20df5e9320de6425fb5ca3d412eb4908b30490de31bd70af2aac862f906ffb82f6638001e6222';
    private $url = 'https://api-demo.airwallex.com';
    private $token;

    /**
     * @Inject()
     * @var HttpService
     */
    private $httpService;

    public function __construct()
    {
        $this->clientId = env('AIR_WALL_EX_CLIENT_ID', 'eb3H0trTS3GZHxJ2FbqraQ');
        $this->apiKey = env('AIR_WALL_EX_API_KEY', '5a42bf77e6fe27669fa20df5e9320de6425fb5ca3d412eb4908b30490de31bd70af2aac862f906ffb82f6638001e6222');
        $this->url = env('AIR_WALL_EX_URL', 'https://api-demo.airwallex.com');

        $token = redis()->get('airwallexToken');

        if (empty($token)) {
            $token = $this->getToken();

        }
        if (!$token) {
            return false;
        }
        $this->token = $token;

    }


    /**
     * airwallex创建付款意向
     * @param $params
     * @return false|mixed
     */
    public function paymentIntent($params)
    {

        $header = [
            'Content-Type' => 'application/json',
            'Authorization' => ' Bearer ' . $this->token,
        ];
        $url = $this->url . '/api/v1/pa/payment_intents/create';

//        $address = $params['address'];
        $postData = [
            'amount' => $params['order']['price'],//支付金额
            'currency' => 'USD',//币种
            'merchant_order_id' => $params['order']['orderNo'],//商户订单号
            'request_id' => randomSign(),//请求id
//            'customer' => [// 会员信息
//                'address' => [
//                    'city' => $address['city'],
//                    'country_code' => $address['code'],
//                    'postcode' => $address['post_code'],
//                    'state' => $address['state'],
//                    'street' => $address['address'],
//                ],
//                'first_name' => $address['name'] ?? '',
//                'last_name' => $address['last_name'] ?? '',
//                'phone_number' => $address['mobile'],
//                'email' => $address['email'],
//            ],
            'descriptor' => $params['order']['descriptor'],
            'merchant_customer_id' => md5($params['order']['uid']),
//            'return_url' => '',//前端去跳转暂时不用
        ];

        return $this->httpService->post($url, $postData, $header);

    }


    /**
     * 查找订单记录
     * @param $payId
     * @return mixed|void
     */
    public function findOrder($payId)
    {
        $header = [
            'Content-Type' => 'application/json',
            'Authorization' => ' Bearer ' . $this->token,
        ];
        $url = $this->url . '/api/v1/pa/payment_intents/' . $payId;


        $result = $this->httpService->get($url, [], $header);
        if ($result) {
            return $result;
        } else {
            recordExceptionLog('airwallex', $result);
            return [];
        }

    }


    public function createSubscriptions()
    {
        $header = $this->commonJsonHeader();

        $postData = [
            'request_id' => randomSign(),//请求id
            'customer_id' => 'cus_hkdmkhcllgjafi9rrmt',
            'items' => [[
                'price_id' => 'pri_hkdmjc96fgjh2jxj8w8',
            ]],
            'payment_consent_id' => 'cst_hkdmd2rwlgjgxyd7m23',
            'recurring' => [
                'period_unit' => 'DAY'
            ]
        ];

        $url = $this->url . '/api/v1/subscriptions/create';
        return $this->httpService->post($url, $postData, $header);
    }


    /**
     * 创建用户
     * @param $uid
     * @return false|mixed
     */
    public function createCustomer($uid)
    {

        $header = $this->commonJsonHeader();

        $postData = [
            'request_id' => randomSign(),//请求id
            'merchant_customer_id' => md5($uid),
        ];

        $url = $this->url . '/api/v1/pa/customers/create';
        return $this->httpService->post($url, $postData, $header);


    }


    public function generateClientSecret($id)
    {

        $header = $this->commonJsonHeader();

        $url = $this->url . '/api/v1/pa/customers/' . $id . '/generate_client_secret';

        return $this->httpService->get($url, [], $header);


    }


    public function createProduct()
    {
        $header = $this->commonJsonHeader();

        $postData = [
            'request_id' => randomSign(),//请求id
            'name' => 'one day free',
        ];

        $url = $this->url . '/api/v1/products/create';
        return $this->httpService->post($url, $postData, $header);


    }


    public function createPaymentConsent()
    {
        $header = $this->commonJsonHeader();

        $postData = [
            'request_id' => randomSign(),//请求id
            'customer_id' => 'cus_hkdmkhcllgjafi9rrmt',
            'metadata' => [
                'foo' => 'bar'
            ],
//            "connected_account_id"=>"acct_Kd7tpGUkNzGoaNoFCHSiGg",
            'next_triggered_by' => 'merchant',
            'merchant_trigger_reason' => 'unscheduled'
        ];

        var_dump($postData);
        $url = $this->url . '/api/v1/pa/payment_consents/create';
        return $this->httpService->post($url, $postData, $header);

    }


    public function paymentConsentsList()
    {
        $header = $this->commonJsonHeader();

        $query = [
            'customer_id' => 'cus_hkdmkhcllgjafi9rrmt',
            'next_triggered_by' => 'merchant',
            'status' => 'VERIFIED'
        ];


        $url = $this->url . '/api/v1/pa/payment_consents';
        return $this->httpService->get($url,$query, $header);
    }


    public function createPrice()
    {
        $header = $this->commonJsonHeader();

        $postData = [
            'request_id' => randomSign(),//请求id
            'active' => true,
            'currency' => "USD",
            'description' => "Standard option: $10 / month.",
            'pricing_model' => "per_unit",
            'product_id' => "prd_hkdmjc96fgjafvnumly",
            'name' => "Standard option",
            'recurring' => [
                'period' => 1,
                'period_unit' => 'DAY'//DAY, WEEK, MONTH or YEAR.
            ],
            'unit_amount' => '0.96'
        ];

        $url = $this->url . '/api/v1/prices/create';
        return $this->httpService->post($url, $postData, $header);

    }


    /**
     * airwallex 获取授权token
     * @return false|mixed
     */
    private function getToken()
    {

        $header = [
            'Content-Type' => 'application/json',
            'x-client-id' => $this->clientId,
            'x-api-key' => $this->apiKey,
        ];
        $url = $this->url . '/api/v1/authentication/login';

        $result = $this->httpService->post($url, [], $header);
        if (isExistence($result, ['token'])) {
            redis()->set('airwallexToken', $result['token'], '1200');
            return $result['token'];
        } else {
            recordExceptionLog('airwallex/getToken', $result);
            return false;
        }
    }


    /**
     * 通用的header 设置
     * @return string[]
     */
    public function commonJsonHeader(): array
    {
        return [
            'Content-Type' => 'application/json',
            'Authorization' => ' Bearer ' . $this->token,
        ];
    }


}
